import React from 'react'
import { inject, observer } from 'mobx-react';
import { toJS } from "mobx"
import { List, Checkbox, Bubble, Icon, DatePicker, Modal, ActivityIndicator, Tools } from 'weaver-mobile'
import { Form, RouteLayout, ListPage } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom'
import cloneDeep from 'lodash/cloneDeep';

const ButtonGroup = RouteLayout.ButtonGroup;
const AgreeItem = Checkbox.AgreeItem;
const FormItem = List.FormItem;
const { DatePickerInput } = DatePicker;
const getLabel = Tools.getLabel;
const template = {
    default: [
        {
            key: 'col1',
            configs: [
                {
                    key: 'col1_row1',
                    configs: [
                        { key: 'agentuidSpan' },
                        {
                            key: 'agentuidspan',
                            className: "hrmName",//点击人员姓名链接到人员卡片
                        },
                    ],
                },
                {
                    key: 'col1_row2',
                    configs: [
                        { key: 'isCreateAgenterSpan' },
                        {
                            key: 'isCreateAgenter',
                            className: "deepGray",
                        },
                    ],
                },
                {
                    key: 'col1_row3',
                    configs: [
                        { key: 'isSysCreateAgenterSpan' },
                        {
                            key: 'isSysCreateAgenter',
                            className: "deepGray",
                        },
                    ],
                },
                {
                    key: 'col1_row4',
                    configs: [
                        { key: 'isProxyDealSpan' },
                        {
                            key: 'isProxyDeal',
                            className: "deepGray",
                        },
                    ],
                },
                {
                    key: 'col1_row5',
                    configs: [
                        { key: 'isPendThingSpan' },
                        {
                            key: 'isPendThingstr',
                            // key: 'isPendThing',
                            className: "deepGray",
                        },
                    ],
                },
                {
                    key: 'col1_row6',
                    configs: [
                        { key: 'conditioncnSpan' },
                        {
                            key: 'conditioncn',
                            className: "deepGray",
                        },
                    ],
                },
                {
                    key: 'col1_row7',
                    configs: [
                        { key: 'batchSpan' },
                        {
                            key: 'agentbatch',
                            className: "deepGray",
                        },
                    ],
                },

            ],
        },
    ],
};
@inject('wfAgentStore')
@withRouter
@observer
export default class EditAgent extends React.Component {
    componentWillMount() {
        const { location, wfAgentStore } = this.props;
        const { getPageTitle } = wfAgentStore;
        const { pathname = "" } = location;
        getPageTitle(pathname);
    }
    componentWillUpdate() {
        const { location, wfAgentStore } = this.props;
        const { getPageTitle } = wfAgentStore;
        const { pathname = "" } = location;
        getPageTitle(pathname);
    }
    componentWillUnmount() {
        const { setEditAgent } = this.props.wfAgentStore;
        setEditAgent({ isSelectedAll: false, selectedRowKeys: [] })
    }
    getSearchs = () => {
        const { editAgent, setEditAgent } = this.props.wfAgentStore;
        const { form, fields, beginTime, beginDate, endDate, endTime } = editAgent;
        let items = [];
        let date = new Date();
        let month = '' + (date.getMonth() + 1);
        let day = '' + date.getDate();
        let year = '' + date.getFullYear();
        let hour = '' + date.getHours();
        let min = '' + date.getMinutes();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        if (hour.length < 2) hour = '0' + hour;
        if (min.length < 2) min = '0' + min;
        let nowDate = year + "-" + (date.getMonth() + 1) + "-" + month + "-" + day;
        // let nowTime = hour + ":" + min;
        if (fields.bagentuid) {
            items.push(
                <Form.Item
                    key={fields.bagentuid.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.bagentuid}
                    onChange={form.onChange}
                />);
        }
        if (fields.workflowid) {
            items.push(
                <Form.Item
                    key={fields.workflowid.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.workflowid}
                    onChange={form.onChange}
                />);
        }
        if (fields.beginDate) {
            items.push(
                <div className="form-time-wrap" key={"beginDate"}>
                    <FormItem
                        key={"beginDate"}
                        wrap="nowrap"
                        label={getLabel(740, "开始日期")}
                        extra={<Icon type="right" />}
                        content={(
                            <DatePickerInput
                                placeholder={getLabel(763, "不限")}
                                mode="date"
                                value={beginDate}
                                minDate={nowDate}
                                maxDate={endDate || "2030-12-30"}
                                key={"beginDate"}
                                onChange={date => {
                                    setEditAgent({ "beginDate": date });
                                }}
                            />
                        )}
                    />
                </div>
            );
        }
        if (fields.beginTime) {
            items.push(
                <div className="form-time-wrap" key={"beginTime"}>
                    <FormItem
                        key={"beginTime"}
                        wrap="nowrap"
                        label={getLabel(500371, "开始时间")}
                        extra={<Icon type="right" />}
                        content={(
                            <DatePickerInput
                                placeholder={getLabel(763, "不限")}
                                mode="time"
                                value={beginTime}
                                key={"beginTime"}
                                onChange={time => {
                                    setEditAgent({ "beginTime": time });
                                }}
                            />
                        )}
                    />
                </div>
            );
        }
        if (fields.endDate) {
            items.push(
                <div className="form-time-wrap" key={"endDate"}>
                    <FormItem
                        key={"endDate"}
                        wrap="nowrap"
                        label={getLabel(741, "结束日期")}
                        extra={<Icon type="right" />}
                        content={(
                            <DatePickerInput
                                placeholder={getLabel(763, "不限")}
                                mode="date"
                                value={endDate}
                                key={"endDate"}
                                minDate={beginDate || nowDate}
                                maxDate="2030-12-30"
                                onChange={date => {
                                    setEditAgent({ "endDate": date });
                                }}
                            />
                        )}
                    />
                </div>
            );
        }
        if (fields.endTime) {
            items.push(
                <div className="form-time-wrap" key={"endTime"}>
                    <FormItem
                        key={"endTime"}
                        wrap="nowrap"
                        label={getLabel(500372, "结束时间")}
                        extra={<Icon type="right" />}
                        content={(
                            <DatePickerInput
                                placeholder={getLabel(763, "不限")}
                                mode="time"
                                value={endTime}
                                key={"endTime"}
                                onChange={time => {
                                    setEditAgent({ "endTime": time });
                                }}
                            />
                        )}
                    />
                </div>
            );
        }

        const group = (
            <Form>
                <List>
                    {items}
                </List>
            </Form>
        )
        return group;
    }

    callback_verifyAgentOverlap = (datas) => {
    }
    callback_saveBatchEditInfo = (datas) => {
    }

    isEqual(a, b) {
        if (a['isPendThing'] === b['isPendThing'] && a['isProxyDeal'] === b['isProxyDeal'] &&
            a['agentuid'] === b['agentuid'] && a['conditionkeyid'] === b['conditionkeyid'] &&
            a['isCreateAgenter'] === b['isCreateAgenter'] && a['conditioncn'] === b['conditioncn'] &&
            a['isSysCreateAgenter'] == b['isSysCreateAgenter'] &&
            Number(a['agentbatch']) === Number(b['agentbatch'])) {
            return true;
        }
        return false;
    }
    onOk = () => {
        const { editAgent, changeItemToSave, setHasRequiredItem, setEditAgent, setSwitchOffAllItem, verifyAgentOverlap } = this.props.wfAgentStore;
        const { form, datas, getDataParams, agentid, beginTime, beginDate, endDate, endTime } = editAgent;
        let formParams = toJS(form.formParams);
        let params = {
            ...getDataParams,
            ...formParams,
            beginTime: beginTime ? beginTime : "",
            beginDate: beginDate ? beginDate : "",
            endDate: endDate ? endDate : "",
            endTime: endTime ? endTime : "",
            ismodifyCondition: true,
        }

        let rownum = 0;
        let newDatas = cloneDeep(toJS(datas));
        let i = 0;
        let hasRequiredUid = false;
        let hasSameName = false;
        let hasSameAgent = false;
        let isSwitchOffAll = false;
        for (i = 0; i < newDatas.length; i++) {
            for (let j = i + 1; j < newDatas.length; j++) {
                if (this.isEqual(newDatas[i], newDatas[j])) {
                    setHasRequiredItem(newDatas[i]);
                    hasSameAgent = true;
                }
            }
            changeItemToSave(newDatas[i]);


            for (let key in newDatas[i]) {
                if (key === "agentuid" && newDatas[i][key] === "") {
                    hasRequiredUid = true;
                    setHasRequiredItem(newDatas[i])
                } else if (key === "agentuid" && newDatas[i][key] === params.bagentuid) {
                    hasSameName = true;
                    setHasRequiredItem(newDatas[i])
                }
                let newkey = "row_" + i + "_" + key;
                if (key === "ruleRelationship") {
                    newDatas[i][key] = "";
                }

                if (key === "agentuidSpan" || key === "isCreateAgenterSpan" || key === "isSysCreateAgenterSpan" || key === "isPendThingSpan" || key === "isProxyDealSpan") {
                    continue;
                }
                params[newkey] = newDatas[i][key];
                if (key === "id") {
                    if (newDatas[i][key].includes("new_")) {
                        params[newkey] = newDatas[i][key].slice(4);
                    }
                }
            }
            if (newDatas[i].isCreateAgenter === "0" && newDatas[i].isSysCreateAgenter === "0" && newDatas[i].isProxyDeal === "0") {
                isSwitchOffAll = true;
                setSwitchOffAllItem(newDatas[i])
            }
            rownum = i;
        }
        params = { ...params, rownum: rownum + 1, agentid: agentid, symbol: "edit" }
        let beginDT = Date.parse(new Date(beginDate + " " + (beginTime ? beginTime : "00:00") + ":00"));
        let endDT = Date.parse(new Date(endDate + " " + (endTime ? endTime : "23:59") + ":00"));
        if (beginTime && !beginDate) {
            Bubble.warning(getLabel(127684, '设置开始时间必须设置开始日期'), 2);
        } else if (endTime && !endDate) {
            Bubble.warning(getLabel(127685, '设置结束时间必须设置结束日期'), 2);
        } else if (endDT <= beginDT) {
            Bubble.warning(getLabel(127683, "结束时间不能小于等于开始时间"), 2);
        } else if (hasRequiredUid) {//代理人信息未填写
            this.goToSetDetail(1);
        } else if (hasSameName) {//代理人与被代理人相同
            this.goToSetDetail(3);
        } else if (isSwitchOffAll) { //【代理流程创建】和【代理流程处理】至少启用一项！
            this.goToSetDetail(2);
        } else if (newDatas.length <= 0) {
            Bubble.warning(getLabel(82681, '请至少添加一行代理设置明细'), 2);
        } else if (hasSameAgent) {
            this.goToSetDetail(4);
        } else {
            //走保存接口
            //先判断有没有重复
            setEditAgent({ saveEditAgentParams: params });
            verifyAgentOverlap(params, this.overLapCallback)
        }
    }

    overLapCallback = (callbakcdatas) => {
        const { setEditAgent, editAgent, saveAgentDetail } = this.props.wfAgentStore;
        const { saveEditAgentParams } = editAgent;
        const { overlapCount = 0 } = callbakcdatas;
        if (overlapCount > 0) {
            let title = <span>{getLabel(82666, "当前代理设置与已有")} <span style={{ fontWeight: "bold", color: "red" }}>{overlapCount}</span> {getLabel(383526, "条代理设置重复请选择重复数据处理方式")}</span>;
            setEditAgent({ title: title, isShowCheckModal: true })
        } else {
            saveAgentDetail(saveEditAgentParams, this.props.history);
        }
    }

    goToSetDetail = (type) => {

        ////弹出确认框提示要不要改，这里是可以用的
        // let dom;
        // let title = "";
        // if (type === 1) {
        //     title = "必要信息不完整";
        //     dom = <span>存在未填<span style={{ fontWeight: "bold" }}>[代理人]</span>的信息！</span>;
        // } else if (type === 2) {
        //     title = "【代理流程创建】和【代理流程处理】至少启用一项！";
        //     dom = "";
        // } else if (type === 3) {
        //     title = "被代理人、代理人信息相同！";
        //     dom = "";
        // } else if (type === 4) {
        //     title = "存在批次相同的重复代理设置，请检查设置!";
        //     dom = "";
        // }
        // Modal.alert(
        //     title,
        //     dom,
        //     [
        //         { text: "取消", onPress: () => { console && console.log("cancle") } },
        //         {
        //             text: "去编辑", onPress: () => {
        //                 const { editAgent, setEditAgent, changeItemToFormValue, changeItemToBool, checkHasP_N } = this.props.wfAgentStore;
        //                 const { detailForm, conditioninfo, hasRequiredItem, switchOffAllItem } = editAgent;
        //                 let newItem = {};
        //                 if (type === 1 || type === 3 || type === 4) {
        //                     newItem = { ...toJS(hasRequiredItem) };
        //                 } else if (type === 2) {
        //                     newItem = { ...toJS(switchOffAllItem) };
        //                 }
        //                 newItem.agentuid = { value: [{ id: newItem.agentuid, name: newItem.agentuidspan }] }
        //                 changeItemToBool(newItem);
        //                 if (detailForm.isInit) {
        //                     let newForm = new Form.Store();
        //                     newForm.initForm(conditioninfo, "/agent/editDetails")
        //                     for (let key in newItem) {
        //                         if (typeof newItem[key] === "string") {
        //                             newItem[key] = { value: newItem[key] };
        //                         }
        //                     }
        //                     newForm.updateFields(newItem);
        //                     setEditAgent({ detailForm: newForm })
        //                 }
        //                 //判断有无上一行
        //                 checkHasP_N(newItem.id);
        //                 setEditAgent({ detailDataId: newItem.id })
        //                 this.props.history.push("/agent/editDetails")
        //             }
        //         },
        //     ])
        if (type === 1) {
            Bubble.warning(getLabel(391142, "必要信息不完整"), 2);
        } else if (type === 2) {
            Bubble.warning(getLabel(391143, "【代理流程创建】和【代理流程处理】至少启用一项！"), 2);
        } else if (type === 3) {
            Bubble.warning(getLabel(391144, "被代理人、代理人不能相同"), 2);
        } else if (type === 4) {
            Bubble.warning(getLabel(391145, "存在批次相同的重复代理设置，请检查设置!"), 2);
        }
        const { editAgent, setEditAgent, changeItemToBool, checkHasP_N } = this.props.wfAgentStore;
        const { detailForm, conditioninfo, hasRequiredItem, switchOffAllItem } = editAgent;
        let newItem = {};
        if (type === 1 || type === 3 || type === 4) {
            newItem = { ...toJS(hasRequiredItem) };
        } else if (type === 2) {
            newItem = { ...toJS(switchOffAllItem) };
        }
        newItem.agentuid = { value: [{ id: newItem.agentuid, name: newItem.agentuidspan }] }
        changeItemToBool(newItem);
        if (detailForm.isInit) {
            let newForm = new Form.Store();
            newForm.initForm(conditioninfo, "/agent/editDetails")
            for (let key in newItem) {
                if (typeof newItem[key] === "string") {
                    newItem[key] = { value: newItem[key] };
                }
            }
            newForm.updateFields(newItem);
            setEditAgent({ detailForm: newForm })
        }
        //判断有无上一行
        checkHasP_N(newItem.id);
        // CONSOLE
        setEditAgent({ detailDataId: newItem.id.value })
        this.props.history.push("/agent/editDetails")
    }

    getTable = () => {
        const { editAgent, addAgenterMsg, deleteLine } = this.props.wfAgentStore;
        const { datas, selectedRowKeys, isSelectedAll } = editAgent;
        let items = [];
        toJS(datas).map(item => {
            let flag = false;
            if (toJS(selectedRowKeys).includes(item.id)) {
                flag = true;
            }
            if (item.agentbatch) {
                let newArr = item.agentbatch.split(".");
                if (newArr.length === 0) {
                    item.agentbatch = "0.00";
                } else if (newArr.length === 1) {
                    item.agentbatch = parseFloat(item.agentbatch, 10).toFixed(2);
                } else if (newArr.length > 1) {
                    if (newArr[1].length === 1) {
                        newArr[1] = newArr[1] + "0";
                    }
                    newArr = [newArr[0], newArr[1]]
                    item.agentbatch = newArr.join(".");
                    item.agentbatch = parseFloat(item.agentbatch, 10).toFixed(2);
                }
            }
            if (item.isProxyDeal === getLabel(161,"否")) {
                item.isPendThingstr = "";
            } else {
                item.isPendThingstr = item.isPendThing;
            }

            items.push(
                <ListPage.Item
                    key={item.id}
                    data={item}
                    showCheck={true}
                    template={template}
                    checked={flag}
                    onSelect={(isChecked) => {
                        const { setEditAgent, editAgent } = this.props.wfAgentStore;
                        const { selectedRowKeys, datas } = editAgent;
                        let arrdatas = toJS(datas);
                        let arr = [...toJS(selectedRowKeys)];
                        if (arr.includes(item.id)) {
                            arr.splice(arr.indexOf(item.id), 1);
                        } else {
                            arr.push(item.id);
                        }
                        setEditAgent({ selectedRowKeys: arr })
                        if (arrdatas.length !== arr.length) {
                            setEditAgent({ isSelectedAll: false })
                        } else {
                            setEditAgent({ isSelectedAll: true });
                        }
                    }}
                    onClick={(item) => {
                        const { editAgent, setEditAgent, changeItemToFormValue, checkHasP_N } = this.props.wfAgentStore;
                        const { detailForm, conditioninfo } = editAgent;
                        let newItem = { ...item };
                        newItem.agentuid = { value: [{ id: newItem.agentuid, name: newItem.agentuidspan }] }
                        changeItemToFormValue(newItem);
                        if (detailForm.isInit) {
                            let newForm = new Form.Store();
                            conditioninfo[0].items.map(_ie => {
                                if (_ie.domkey[0] === "conditioncn") {
                                    if (!_ie.label.includes(` （${getLabel(520343,"移动端不支持代理流程处理条件设置")}）`)) {
                                        _ie.label = _ie.label + ` （${getLabel(520343, "移动端不支持代理流程处理条件设置")}）`;
                                    }
                                }
                                return _ie;
                            })
                            newForm.initForm(conditioninfo, "/agent/editDetails")
                            newForm.updateFields(newItem);
                            setEditAgent({ detailForm: newForm })
                        }
                        //判断有无上一行
                        checkHasP_N(item.id);
                        setEditAgent({ detailDataId: item.id })
                        this.props.history.push("/agent/editDetails")
                    }}
                >
                </ListPage.Item>
            )
            return items;
        })
        return (
            <div>
                <div className="details-title">{getLabel(387394, "详细信息")}</div>
                <div className="details-operation">
                    <AgreeItem
                        checked={isSelectedAll}
                        onClick={() => {
                            const { editAgent, setEditAgent } = this.props.wfAgentStore;
                            const { selectedRowKeys, datas } = editAgent;

                            let arr = [];
                            toJS(datas).map(item => {
                                arr.push(item.id);
                                return arr;
                            })
                            if (arr.length === toJS(selectedRowKeys).length) {
                                setEditAgent({ selectedRowKeys: [], isSelectedAll: false });
                            } else {
                                setEditAgent({ selectedRowKeys: arr, isSelectedAll: true });
                            }
                        }}
                    >
                        {getLabel(556, "全选")}
                    </AgreeItem>
                    <div className="agnenter-icon-part" >
                        <Icon type="shanchu" className="agenter-icon icon-shanchu" onClick={() => { deleteLine(toJS(selectedRowKeys), this.props.history, false) }} />
                        <Icon type="tianjia" className="agenter-icon icon-tianjia " onClick={addAgenterMsg} />
                    </div>
                </div>
                <List className="details-list">
                    {items}
                </List>
            </div>
        )
    }

    onCheckBoxChange = (val) => {
        const { setEditAgent } = this.props.wfAgentStore;
        setEditAgent({ radioChecked: val })
    }

    render() {
        const { wfAgentStore, setEditAgent } = this.props;
        const { editAgent } = wfAgentStore;
        const { isShowLoading, isShowCheckModal, title, saveEditAgentParams, radioChecked } = editAgent;
        const btns = [{
            key: 'save',
            text: getLabel(86, "保存"),
            onClick: this.onOk,
            type: 'primary',
        }]
        return (
            <div style={{ height: "100%" }} className="editAgent">
                <div className='wf-agent-editagent-wrap' >
                    <div className="addAgent-form" >
                        {this.getSearchs()}
                        {this.getTable()}
                        {isShowLoading &&
                            <ActivityIndicator
                                toast
                            text={getLabel(500408 , "加载中...")}
                                animating={isShowLoading}
                            />}
                        {isShowCheckModal &&
                            <Modal
                                visible={isShowCheckModal}
                                transparent
                                title={title}
                                footer={[
                                    {
                                        text: getLabel(201, '取消'), onPress: () => {
                                            setEditAgent({ title: "", isShowCheckModal: false, radioChecked: 1 })

                                        }
                                    },
                                    {
                                        text: getLabel(826, '确定'), onPress: () => {
                                            this.saveAgentDetail({ ...toJS(saveEditAgentParams), overlapMethod: radioChecked });
                                        }
                                    }
                                ]}
                            >
                                <div>
                                    <AgreeItem
                                        defaultChecked
                                        checked={radioChecked === 1 ? true : false}
                                        onChange={() => this.onCheckBoxChange(1)}
                                    ><span>{getLabel(82669, "从新保存的代理设置中去除重复设置内容")}</span>
                                    </AgreeItem>
                                    <AgreeItem
                                        checked={radioChecked === 2 ? true : false}
                                        onChange={() => this.onCheckBoxChange(2)}
                                    ><span>{getLabel(82670, "以新保存的代理设置替换已有重复的代理设置")}</span>
                                    </AgreeItem>
                                    {/**下面的代码也是可以达到相同的效果 */}
                                    {/* <Radio checked={radioChecked === 1 ? true : false} onChange={() => this.onCheckBoxChange(1)}>Agree</Radio>
                        <Radio checked={radioChecked === 2 ? true : false} onChange={() => this.onCheckBoxChange(2)}>Agree</Radio> */}
                                </div>
                            </Modal>
                        }

                    </div>
                    <div className='wf-agent-editagent-button-group'>
                        <ButtonGroup data={btns} />
                    </div>
                </div>
            </div>
        )
    }
}